//
//  WSEmoticonView.swift
//  emoticonView
//
//  Created by 武莎莎 on 15/9/14.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

private let WSEmoticonKeyboardCellID = "WSEmoticonKeyboardCell"

class WSEmoticonKeyboard: UIViewController, UICollectionViewDataSource,UICollectionViewDelegate {
    
    // 选中按钮之后的闭包回调
    var selectedEmoticonCallBack:(emoticon:WSEmoticons)->()
    
    init(selectedEmoticon: (emoticon:WSEmoticons)->()) {
        // 初始化闭包
        selectedEmoticonCallBack = selectedEmoticon
        super.init(nibName: nil, bundle: nil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.redColor()
        setupUI()
    }

    @objc private func clickedItem(item:UIBarButtonItem) {
        // 点击toolBar中的item正好对应者表情包的分组
        let indexPath = NSIndexPath(forRow: 0, inSection: item.tag)
        // 让collectionView滚动到指定的位置
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    private func setupUI() {
        view.addSubview(collectionView)
        view.addSubview(toolBar)

        // 添加约束
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        let viewDict = ["cv":collectionView,"tb":toolBar]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: [], metrics: nil, views: viewDict))
        
        prepareToolbar()
        prepareCollectionView()
    }
    private func prepareCollectionView() {
        collectionView.backgroundColor = UIColor.whiteColor()
        // 注册可重用cell
        collectionView.registerClass(WSEmoticonCell.self, forCellWithReuseIdentifier: WSEmoticonKeyboardCellID)
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
    private func prepareToolbar() {
        toolBar.tintColor = UIColor.darkGrayColor()
        
        var index = 0
        var items = [UIBarButtonItem]()
        for p in emoticonViewModel.packages {
            let item = UIBarButtonItem(title: p.group_name_cn, style: UIBarButtonItemStyle.Plain, target: self, action: "clickedItem:")
            item.tag = index++
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        toolBar.items = items
    }
    // MARK:懒加载控件：注意初始化collectionView的方法
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: WSEmoticonFlowLayout())
    private lazy var toolBar = UIToolbar()
    // 数据源
    private var emoticonViewModel:WSEmoticonViewModel = {
        let et = WSEmoticonViewModel()
        et.loadPackages()
        return et
    }()
}

extension WSEmoticonKeyboard {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return emoticonViewModel.packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return emoticonViewModel.packages[section].emoticons.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WSEmoticonKeyboardCellID, forIndexPath: indexPath) as! WSEmoticonCell
        
        cell.emoticon = emoticonViewModel.emoticonWithIndexpath(indexPath)
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    
        // 调用闭包，返回数据
        selectedEmoticonCallBack(emoticon: emoticonViewModel.emoticonWithIndexpath(indexPath))
    }
}
// MARK: 自定义flowlayout
private class WSEmoticonFlowLayout: UICollectionViewFlowLayout {
    
    // 第一次设置布局的时候会调用
    private override func prepareLayout() {
    
        let w = (collectionView?.bounds.size.width)! / 7
        let margin = (collectionView!.bounds.size.height - 3 * w) * 0.499
        
        itemSize = CGSizeMake(w, w)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        sectionInset = UIEdgeInsetsMake(margin, 0, margin, 0)
        
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.pagingEnabled = true
    }
}
// MARK: 自定义cell
private class WSEmoticonCell: UICollectionViewCell {
   
    var emoticon:WSEmoticons? {
        didSet{
            emoticonBtn.setImage(UIImage(named:emoticon!.imagePath), forState: UIControlState.Normal)
            emoticonBtn.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            if emoticon!.isRemove {
                // TODO: 
                //显示无效的图片名：CUICatalog: Invalid asset name supplied:
                emoticonBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
        }
    }
    private lazy var emoticonBtn:UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor.whiteColor()
        btn.frame = CGRectInset(self.bounds, 4, 4)
        btn.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        btn.userInteractionEnabled = false
        
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(emoticonBtn)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
